<template>
  <div class="warpper-box staffList">
    <enterprise-select v-if="userInfo.type == 4" ref="enterprise"
      @enterpriseChange="enterpriseChange"></enterprise-select>
    <a-card style="margin-top: 10px;">
      <div style="display: flex;justify-content: flex-start;align-items: flex-start;">
        <form-create v-model="params.fApi" :rule="params.rule" :option="params.option" />
        <org-select ref="orgSelect" @on-tree="treeCall"></org-select>
        <span style="display: flex;justify-content: flex-start;align-items: center;">
          <span style="flex-shrink: 0;margin-right: 8px;color: rgba(0, 0, 0, 0.85);">花名册:</span>
          <a-select show-search v-model="groupId" :filter-option="filterOption" placeholder="选择花名册"
            style="width: 160px;margin: 6px 10px 0 0;">
            <a-select-option v-for="d in groupData" :key="d.groupId">
              {{ d.name }}
            </a-select-option>
          </a-select>
        </span>
      </div>
      <a-button type="primary" icon="search" @click="loadTable(true)">搜索</a-button>
      <a-button type="primary" icon="setting" @click="reset">重置</a-button>
    </a-card>
    <a-card style="margin-top: 10px;">
      <a-row>
        <a-col :span="18">
          <div>
            <span class="staffTitle">员工列表</span>
            <a-button @click="$refs.handleLeave.init(enterpriseId, selectedRows)" type="danger" icon="apartment"
              :disabled="selectedRowKeys.length == 0">批量办理离职</a-button>
            <a-button @click="staffExport" type="primary" icon="file-excel">导出Execl</a-button>
            <a-button @click="openAnnex" type="warning" icon="file-excel">上传员工附件</a-button>
          </div>
        </a-col>
        <a-col :span="6" style="text-align: right;">
          <a-button type="primary" icon="team" ghost @click="$refs.groupList.init(enterpriseId)">花名册管理</a-button>
          <a-button type="primary" icon="plus" ghost @click="addGroup"
            :disabled="selectedRowKeys.length == 0">加入花名册</a-button>
        </a-col>
      </a-row>
      <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
        @change="handleTableChange" rowKey="id"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <!-- 操作栏-->
        <span slot="action" slot-scope="text, record">
          <!-- 编辑模块 | 字段 -->
          <a @click="staffDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="transferStaff(record)">调转</a>
          <a-divider type="vertical" v-show="record.groupName" />
          <a-popconfirm v-show="record.groupName" title="确认移除?" ok-text="确认" cancel-text="取消"
            @confirm="removeGroup(record)">
            <a>移除花名册</a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-card>
    <!-- 花名册列表 -->
    <group-list ref="groupList" @on-ok="resetGroup"></group-list>
    <!-- 批量办理离职 -->
    <handle-leave ref="handleLeave" @on-ok="reset"></handle-leave>
    <!-- 企业组织 -->
    <org-tree ref="orgTree" @on-tree="orgTreeCall"></org-tree>
    <!-- 加入花名册弹窗 -->
    <a-modal v-model="isAddGroup" title="加入花名册" @ok="addGroupSubmit">
      <a-select show-search v-model="addGroupId" :filter-option="filterOption" placeholder="选择花名册" style="width: 240px">
        <a-select-option v-for="d in groupData" :key="d.groupId">
          {{ d.name }}
        </a-select-option>
      </a-select>
    </a-modal>
    <!-- 上传员工附件 -->
    <a-modal v-model="isAnnex" title="附件上传" @ok="annexSubmit">
      <a-button type="primary" @click="importAnnex" style="margin: 0 0 10px;width: 160px;">上传文件</a-button>
      <input type="file" ref="fileExcel" @change="importAnnexHandle" style="display: none;" multiple="multiple" />
      <a-alert message="支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB；批量上传协议名称命名规则：身份证号码（500110xxxxxxx1316.pdf）"
        type="info" />
      <div class="annexList">
        <div class="list" v-for="(item, index) in policyFileList" :key="item.fileId">
          <span><a-icon type="file" style="margin-right: 6px;" />{{ item.fileName }}</span>
          <a-icon type="delete" style="cursor: pointer;" @click="deteleAnnex(index)" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import store from '@/store'
import GroupList from "./group_list"
import HandleLeave from "./handle_leave.vue"
import OrgSelect from "@/components/human/orgSelect.vue"
import OrgTree from "@/components/human/orgTree.vue"
import EnterpriseSelect from "@/components/human/enterpriseSelect.vue"
import {
  PARAMS_STAFF,
  COLUMNS_STAFF
} from "./form"
import {
  OPTION_BLOCK,
  OPTION_INLINE
} from "../base_form"
import {
  getTablePage,
  getStaffExport,
  getStaffGroup,
  addStaffToGroup,
  removeStaffFromGroup,
  getStaffTransfer,
  enterpriseStaffFileAdd,
  checkFileName
} from "@/api/human/relationStaff"
import { uploadNewFile } from "@/api/manage/base"
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'staffList',
  components: {
    GroupList,
    OrgSelect,
    OrgTree,
    EnterpriseSelect,
    HandleLeave
  },
  data() {
    return {
      params: {
        fApi: {},
        rule: PARAMS_STAFF,
        option: OPTION_INLINE,
      },
      table: {
        columns: COLUMNS_STAFF,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },

      orgId: "", // 组织id
      groupId: "", // 花名册id
      enterpriseId: "", // 企业id
      enterpriseData: [], // 客户列表

      isAddGroup: false, // 加入花名册开关
      groupData: [], // 花名册列表
      addGroupId: "", // 加入花名册id
      selectedRowKeys: [], // 选择的table数据id
      selectedRows: [], // 选择的table数据

      treeName: [],
      treeKey: [],
      transferStaffId: "", // 调转接口所需要员工id

      count: 0,
      isAnnex: false,
      policyFileList: [], // 附件列表
    }
  },
  filters: {
    filterMore(value, num) {
      if (!value) return ''
      if (value.length > num) {
        return value.slice(0, num) + '...'
      }
      return value
    }
  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
    if (this.userInfo.type == 4) {
      this.$refs.enterprise.getEnterpriseData();
    } else {
      this.enterpriseId = this.userInfo.relationId
      this.$refs.orgSelect.add(this.userInfo.relationId);
      this.groupTable();
      this.loadTable(true);
    }
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {

  },
  methods: {
    // table复选框选择
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 添加花名册开关
    addGroup() {
      this.isAddGroup = true;
    },
    // 移除花名册
    async removeGroup(row) {
      let params = {
        ids: [row.id]
      };
      const { code } = await removeStaffFromGroup(params);
      if (code === '1') {
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 添加花名册
    async addGroupSubmit() {
      let params = {};
      params.groupId = this.addGroupId;
      params.ids = this.selectedRowKeys;
      const { code, data } = await addStaffToGroup(params);
      if (code === '1') {
        this.isAddGroup = false;
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    transferStaff(row) {
      this.$refs.orgTree.add(this.enterpriseId, this.treeKey, this.treeName);
      this.transferStaffId = row.staffId;
    },
    openAnnex() {
      this.isAnnex = true;
      this.policyFileList = [];
      this.count = 0;
    },
    // 导入表单
    importAnnex() {
      this.$refs.fileExcel.click();
    },
    async importAnnexHandle(e) {
      e.preventDefault();
      let _this = this;
      let fileList = e.target.files;
      if (fileList.length === 0) {
        e.target.value = "";
        return;
      }
      if (fileList.length > 100) {
        _this.$message.error("一次上传最多100个文件");
        e.target.value = "";
        return;
      }
      this.count = 0;
      for (let i = 0; i < fileList.length; i++) {
        let isLt5M = fileList[i].size / 1024 / 1024 < 20
        if (!isLt5M) {
          this.count++;
          this.$message.error('单个文件大小不能超过 20MB!');
          return;
        }
        let fileName = fileList[i].name;
        let formData = new FormData();
        formData.append("file", fileList[i]);
        formData.append("dirName", '员工附件');
        checkFileName({
          enterpriseId: _this.enterpriseId,
          fileName: fileName
        }).then(res => {
          if (res.code == '1' && res.data) {
            uploadNewFile(formData).then(response => {
              const data = response.data;
              _this.count++;
              _this.policyFileList.push({
                fileUrl: data,
                fileName: fileName
              })
              if (_this.count == fileList.length) {
                _this.count = 100;
                e.target.value = "";
                _this.$message.success("操作成功");
              }
            }).catch(error => {
              _this.count = 0;
              e.target.value = "";
              _this.$message.error("网络不稳定，请重试或联系管理员");
            })
          } else {
            _this.$message.warning("请按照协议名称命名规则选择文件");
          }
        })
      }
    },
    // 删除附件
    async deteleAnnex(index) {
      this.policyFileList.splice(index, 1);
      this.$message.success('删除成功');
    },
    // 附件上传
    async annexSubmit() {
      if (this.policyFileList.length == 0) {
        return this.$message.warning("请选择附件上传");
      }
      const { code } = await enterpriseStaffFileAdd({
        enterpriseId: this.enterpriseId,
        list: this.policyFileList
      });
      if (code === '1') {
        this.isAnnex = false;
        this.$message.success('操作成功')
        this.$emit('on-ok')
      }
    },
    // 组织结构回调
    async orgTreeCall(info) {
      if (info.name.length > 0) {
        const { code } = await getStaffTransfer({
          staffId: this.transferStaffId,
          orgIds: info.key
        })
        if (code == '1') {
          this.$message.success("操作成功");
          this.loadTable(true);
        }
      } else {
        this.$message.warning("请选择组织")
      }
    },
    // 获取花名册列表
    async groupTable() {
      let params = {};
      params.enterpriseId = this.enterpriseId;
      const { code, data } = await getStaffGroup(params);
      if (code === '1') {
        this.groupData = data;
        if (data) {
          this.addGroupId = data[0].groupId;
        }
      }
    },
    // 跳转员工详情
    staffDetail(row) {
      this.$router.push({
        name: 'humanResourcesRelationStaffInfoCode', query: {
          staffId: row.staffId,
          enterpriseId: this.enterpriseId,
          idCard: row.idCard,
          type: "1"
        }
      });
    },
    // 获取企业员工列表
    async loadTable(flag) {
      let params = this.params.fApi.formData();
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
        this.selectedRows = [];
        this.selectedRowKeys = [];
      }
      params.enterpriseId = this.enterpriseId;
      params.groupId = this.groupId;
      params.orgId = this.orgId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getTablePage(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 导出企业员工
    staffExport() {
      let params = this.params.fApi.formData();
      params.enterpriseId = this.enterpriseId;
      params.groupId = this.groupId;
      params.orgId = this.orgId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      getStaffExport(params).then(res => {
        const blob = new Blob([res]);
        const fileName = '企业员工列表.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 组织回调
    treeCall(info) {
      this.orgId = info.key;
    },
    // 企业选择回调
    enterpriseChange(value) {
      this.enterpriseId = value;
      this.$refs.orgSelect.add(value);
      this.loadTable(true);
      this.groupTable();
    },
    resetGroup() {
      this.groupTable()
    },
    reset() {
      this.params.fApi.resetFields();
      this.$refs.orgSelect.reset();
      this.orgId = "";
      this.groupId = "";
      this.loadTable(true);
    }
  }
}
</script>
<style lang="less">
.staffList {
  .staffTitle {
    font-size: 20px;
    color: rgba(0, 0, 0, 0.85);
    display: inline-block;
    vertical-align: middle;
    margin-right: 50px;
    font-weight: 600;
  }
}
.annexList {
  padding-top: 10px;

  .list {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
  }
}
</style>